//
//  MainViewController.swift
//  weibo-01
//
//  Created by 韩家奇 on 15/11/3.
//  Copyright © 2015年 hanjiaqi. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
/// 点击撰写按钮
    ///如果值使用private 运行循环将无法正确的发送消息 会导致程序崩溃
    ///如果是用@objc 修饰符 可以保证循环能后发送消息  函数能够被标记为private
    @objc private func clickComposeButton() {
//        print("点我了")
        // 判断用户是否登录
        var vc: UIViewController
        if UserAccountViewModel.sharedUserAccount.userLogin {
            vc = ComposeViewController()
        } else {
            vc = OAuthViewController()
        }
        
        let nav = UINavigationController(rootViewController: vc)
        
        presentViewController(nav, animated: true, completion: nil)

    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        //添加子控制器
        addChildViewControllers()
        setupComposedButton()
    }
    override func viewWillAppear(animated: Bool) {
        //创建tabBar中所有的按钮
        super.viewWillAppear(animated)
        //将按钮带到最前面
        tabBar.bringSubviewToFront(composedButton)
    }
    /// 懒加载
    lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")


}
//MARK:- 设置界面
extension MainViewController{
    //添加按钮
    private func setupComposedButton() {
        //添加按钮
        tabBar.addSubview(composedButton)
        //调整按钮的位置
        let count = childViewControllers.count
        //每个Button的宽度
        let w = tabBar.bounds.width / CGFloat(count)-1
        composedButton.frame = CGRectInset(tabBar.bounds, 2*w, 0)
        //添加按钮的监听方法
        composedButton.addTarget(self, action: "clickComposeButton", forControlEvents: .TouchUpInside)
    }
    
    private func addChildViewControllers() {
        //给按钮设置颜色 渲染
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    private func addChildViewController(VC: UIViewController,title: String,imageName: String) {
        VC.title = title
        VC.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: VC)
        addChildViewController(nav)
        
    }
}